package com.junlong0716.enjoylearning.ui

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.StudyNotesAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.StudyNoteEntity
import com.junlong0716.enjoylearning.entity.rxevent.RefreshNote
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.getknowledgedemo.decoration.DividerItemNoEndDecoration
import com.junlong0716.module.common.base.BaseActivity
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_note.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class NoteActivity : BaseActivity<StudyRecordPresenter>(), StudyRecordContract.View, BaseQuickAdapter.RequestLoadMoreListener {
    private lateinit var studyNotesAdapter: StudyNotesAdapter
    private lateinit var notesData: ArrayList<StudyNoteEntity>
    private var isLoadingMore = false
    private var currentPage = 1
    private var onePageCount = 10

    override fun beforeSetLayout() {}

    override fun attachPresenter() {
        mPresenter = StudyRecordPresenter()
        mPresenter!!.attachView(this)
    }

    override fun getLayoutId(): Int = R.layout.activity_note

    override fun initView(savedInstanceState: Bundle?) {
        rl_back.setOnClickListener { finish() }

        tv_title.text = "我的笔记"

        srl_refresh.isEnableLoadMore = false

        notesData = ArrayList()
        studyNotesAdapter = StudyNotesAdapter(notesData, R.layout.item_study_notes)
        rv_note.layoutManager = LinearLayoutManager(this)
        rv_note.adapter = studyNotesAdapter
        rv_note.addItemDecoration(DividerItemNoEndDecoration(this, LinearLayoutManager.VERTICAL, 30, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))

        srl_refresh.autoRefresh()

        srl_refresh.setOnRefreshListener {
            isLoadingMore = false
            mPresenter!!.requestStudyNote(this, 1, onePageCount)
        }

        studyNotesAdapter.setOnLoadMoreListener(this, rv_note)


        studyNotesAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view!!.id) {
                R.id.ll_knowledge_content -> {
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", "http://123.127.109.109:8090/file/temp/a/page1.html")
                    intent.putExtra("document_title", notesData[position].knowledgeTitle)
                    intent.putExtra("document_id", notesData[position].knowledgeId)
                    this.startActivity(intent)
                }

                R.id.tv_delete -> {
                    MaterialDialog.Builder(this)
                            .title("是否删除？")
                            .canceledOnTouchOutside(false)
                            .positiveText("是")
                            .negativeText("否")
                            .onPositive { dialog, which ->
                                requestDelNote(position)
                            }
                            .onNegative { dialog, which ->
                                dialog.dismiss()
                            }
                            .show()
                }
                R.id.tv_edit -> {
                    val intent = Intent(this, AddNoteActivity::class.java)
                    intent.putExtra("WEB_ID", notesData[position].knowledgeId)
                    intent.putExtra("SELECT_TEXT", notesData[position].remarks)
                    intent.putExtra("IS_UPDATE_NOTE", true)
                    intent.putExtra("NOTES_CONTENT", notesData[position].noteContent)
                    intent.putExtra("NOTES_ID", notesData[position].id)
                    startActivity(intent)
                }
            }
        }
    }

    private fun requestDelNote(position: Int) {
        val map = HashMap<String, Int>()
        map["id"] = notesData[position].id
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_DEL_NOTE)
                .tag(this)
                .upJson(JSONObject(map))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        if (jsonObject.getString("code") == "200") {
                            ToastUtils.showShort("删除成功！")
                            srl_refresh.autoRefresh()
                            RxBus.getDefault().post(RefreshNote())
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("删除失败！")
                    }
                })
    }

    override fun requestStudyNoteSucceed(noteData: ArrayList<StudyNoteEntity>) {
        srl_refresh.finishRefresh()
        if (isLoadingMore) {
            if (noteData.isEmpty()) {
                studyNotesAdapter.loadMoreEnd()
            } else {
                studyNotesAdapter.addData(noteData)
                studyNotesAdapter.loadMoreComplete()
            }
        } else {
            notesData.clear()
            if (noteData.isEmpty()){
                studyNotesAdapter.emptyView = LayoutInflater.from(this).inflate(R.layout.view_empty, null)
            }
            notesData.addAll(noteData)
            studyNotesAdapter.notifyDataSetChanged()
            //onLoadMoreRequested()
        }
    }

    override fun requestQueryMyStudyTimeSucceed(dayList: ArrayList<String>, totalTime: String) {

    }

    override fun onLoadMoreRequested() {
        isLoadingMore = true
        currentPage += 1
        mPresenter!!.requestStudyNote(this, currentPage, onePageCount)
    }

    override fun bindService() {

    }
}
